<template>
  <div class="Background">
    <div class="dashboard-container">
      <!-- 图表区域 -->
      <div class="chart-section">
        <!-- 饼图 -->
        <div class="pie-chart">
          <PieChart :data="pieData" :totalEvents="totalEvents" />
        </div>

        <!-- 柱状图 -->
        <div class="bar-chart">
          <BarChart :data="barData" />
        </div>
      </div>

      <!-- 事件列表 -->
      <div class="event-section">
        <div class="filter-controls">
          <input v-model="searchQuery" placeholder="搜索事件..." class="search-input">
          <div class="t_sort">排序:</div>
          <select v-model="sortOrder" class="sort-select" @change="sortEvents">
            <option value="date">时间</option>
            <option value="comments">评论数</option>
          </select>
          <select v-model="pageSize" class="page-size-select">
            <option v-for="size in pageSizes" :key="size" :value="size">{{ size }}条/页</option>
          </select>
        </div>

        <EventList :events="paginatedEvents" @item-click="handleItemClick" />
        <!-- 事件详情弹窗 -->
        <EventModal :visible="modalVisible" :event="selectedEvent" @close="modalVisible = false"  @initEvent="initEvent"/>
        <!-- 分页组件 -->
        <div class="pagination-container"> <!-- 新增容器 -->
          <BasePagination :current-page="currentPage" :total-items="filteredEvents.length" :page-size="pageSize"
            @page-change="handlePageChange" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
/* eslint-disable no-unused-vars */
import { ref, computed, watch, onMounted, toRefs } from 'vue'
import PieChart from '../components/sentiment-components/PieChart.vue'
import BarChart from '../components/sentiment-components/BarChart.vue'
import EventList from '../components/sentiment-components/EventList.vue'
import BasePagination from './sentiment-components/BasePagination.vue'
import EventModal from '../components/sentiment-components/EventModal.vue'


import { getAllEvents,eventAnalysisInit } from "../api/analysis"

onMounted(() => {
  getEvents()
})

const mockEvents = ref([])
async function getEvents() {
  const res = await getAllEvents()
  mockEvents.value = res.data;
}

async function initEvent(id) {
  const index = mockEvents.value.findIndex(event => event.id === id);
  mockEvents.value[index].eventstate = -id
  const res = await eventAnalysisInit(id)
  mockEvents.value[index]= res.data
  selectedEvent.value=mockEvents.value[index]
}

for (let i = 0; i < mockEvents.value.length; i++) {
  eventPlatformsCount[mockEvents.value[i].platform]++;
}

const pieData = ref([
  { value: 0, name: 'B站' },
  { value: 0, name: '小红书' },
  { value: 0, name: '微博' },
  { value: 0, name: '知乎' }
])
const barData = ref({
  categories: ['音乐', '科技', '股市', '政策', '游戏', '运动', '学术', '军事', '娱乐', '影视'],
  values: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
})


const currentPage = ref(1)
const pageSize = ref(8)
const pageSizes = [8, 16, 20]
const searchQuery = ref('')
const sortOrder = ref('date') // 新增排序顺序

const filteredEvents = computed(() => {
  return mockEvents.value.filter(event =>
    event.title.includes(searchQuery.value) ||
    event.type.includes(searchQuery.value)
  )
})

const paginatedEvents = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredEvents.value.slice(start, start + pageSize.value)
})

const handlePageChange = (page) => {
  currentPage.value = page
}

// 弹窗状态管理
const modalVisible = ref(false)
const selectedEvent = ref({})

// 处理点击事件
const handleItemClick = (event) => {
  console.log('点击事件', event)
  selectedEvent.value = event  // 传递完整事件对象
  modalVisible.value = true    // 显示弹窗
}

// 计算事件总数
const totalEvents = computed(() => {
  return mockEvents.value.length
})

// 计算每个事件类型的数量
const eventTypesCount = computed(() => {
  let counts = {
    '音乐': 0,
    '科技': 0,
    '股市': 0,
    '政策': 0,
    '游戏': 0,
    '运动': 0,
    '学术': 0,
    '军事': 0,
    '娱乐': 0,
    '影视': 0
  }
  mockEvents.value.forEach(event => { counts[event.type]++; })
  return counts
})

// 更新 barData 的 values
watch(eventTypesCount, (newCounts) => {
  barData.value.values = barData.value.categories.map(category => newCounts[category])
}, { immediate: true })


const eventPlatformsCount = computed(() => {
  const mp = {
    "xhs": "小红书",
    "dy": "抖音",
    "ks": "快手",
    "bili": "B站",
    "wb": "微博",
    "tieba": "贴吧",
    "zhihu": "知乎"
  }
  
  let counts = {
    'B站': 0,
    '小红书': 0,
    '微博': 0,
    '知乎': 0
  }
  mockEvents.value.forEach(event => { counts[mp[event.platform]]++; })
  return counts
})

// 更新 pieData 的 values
watch(eventPlatformsCount, (newCount) => {
  pieData.value.forEach(item => {
    item.value = newCount[item.name];
  });
}, { deep: false, immediate: true });



// 新增排序方法
const sortEvents = () => {
  if (sortOrder.value === 'date') {
    mockEvents.value.sort((a, b) => new Date(b.date) - new Date(a.date))
  } else if (sortOrder.value === 'comments') {
    mockEvents.value.sort((a, b) => b.comments - a.comments)
  }
}
</script>

<style scoped>
.Background {
  width: 100%;
  background-image: url('../background/DBack.jpg');
  background-size: cover;
  background-repeat: no-repeat;
}

.dashboard-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.chart-section {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 30px;
  margin-bottom: 40px;
  height: 400px;
}

.pie-chart,
.bar-chart {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.event-section {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.filter-controls {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #111010;
  border-radius: 4px;
}

.page-size-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.sort-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.t_sort {
  margin-top: 5px;
}

/* 新增样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>